# -*- coding: utf-8 -*-

import weiyi
import sqlite3
import weixin
import time

def publisherget():# 渠道入库
    webdata = weiyi.publisherget()
    if webdata['error'] == '0':
        inviter_list = webdata['data']['inviter_list']['map_data']
        for inviter in inviter_list:
            publishersave(inviter) # 保存或更新
    else:
        print(webdata['msg'])

def publishersave(inviter):#
    conn = sqlite3.connect('taobaokesql.db')
    curs = conn.cursor()
    query = 'SELECT * FROM beian WHERE relation_id = "%s";'%(inviter['relation_id'])
    curs.execute(query)
    sqldata = curs.fetchall()
    if sqldata:
        conn.close()
        print('渠道已存在 id:%s'%(inviter['relation_id']))
        return None
    if 'rtag' in inviter:
        query = 'INSERT INTO beian(openid, relation_app, create_date, account_name, real_name, relation_id, offline_scene, online_scene, note, root_pid) VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s");'%(inviter['rtag'], inviter['relation_app'], inviter['create_date'], inviter['account_name'], inviter['real_name'], inviter['relation_id'],inviter['offline_scene'],inviter['online_scene'], inviter['note'], inviter['root_pid'])
        timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(weixin.templateMsgSend(inviter['rtag'], '会员备案成功！', inviter['real_name'], timestr, '你现在可以进行购物返利了', '如有疑问请联系客服')) # 发送绑定成功消息
    else:
        query = 'INSERT INTO beian(relation_app, create_date, account_name, real_name, relation_id, offline_scene, online_scene, note, root_pid) VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s");'%(inviter['relation_app'], inviter['create_date'], inviter['account_name'], inviter['real_name'], inviter['relation_id'],inviter['offline_scene'],inviter['online_scene'], inviter['note'], inviter['root_pid'])
    curs.execute(query)
    conn.commit()
    conn.close()
    print('渠道收录成功 id:%s'%(inviter['relation_id']))
    return None

publisherget()
